<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
</head>
<body>
    <input type="file" id="file1"/>
    <button id="btnUpload">上传文件按钮</button>
    <br>
    <img src="" alt="" id="img" width="400px" />
    <div class="progress" style="width: 500px; margin: 15px 10px;">
        <div class="progress-bar" style="width:0;" id="percent">
        </div>
      </div>
</body>

<script>
   
    let btn = document.getElementById('btnUpload');
    let percent = document.querySelector('#percent');
    btn.addEventListener('click',function(){
        let file1= document.getElementById('file1').files;
        console.log(file1.length)
        if(file1.length <= 0 ){
            alert('请选择要上传的文件');
        }

        let fd = new FormData();
        fd.append('avatar',file1[0])
        let xhr =  new XMLHttpRequest();
        //监听文件上传的进度
        xhr.upload.onprogress =function(e){
            if(e.lengthComputable){
                let percentComplete = Math.ceil(e.loaded / e.total *100);
                console.log(percentComplete);
                percent.style.width =percentComplete + '%';
                percent.innerHTML = percentComplete;
            }
        }
        xhr.open('POST','http://www.liulongbin.top:3006/api/upload/avatar');
        xhr.send(fd);
        xhr.onreadystatechange = function(){
            if(xhr.readyState == 4 && xhr.status ==200){
                let data =JSON.parse(xhr.responseText)
                if(xhr.status == 200){
                    document.querySelector('#img').src='http://www.liulongbin.top:3006'+ data.url
                }else{
                    alert('上传失败'+ data.message);
                }
            }
        }
    })
</script>
</html>